package com.system.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.common.bean.Address;
import com.system.common.bean.Address;
import com.system.common.bean.User;
import com.system.common.service.IAddressService;
import com.system.common.service.IUserService;
import com.system.user.mapper.AddressMapper;
import com.system.user.mapper.UserMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @DubboReference
    private IUserService userService;
    @Override
    public Address getAddressById(Integer id) {
        return super.getById(id);
    }

    @Override
    public void addAddress(Address address) {
        super.save(address);
    }

    @Override
    public void updateAddress(Address address) {
        super.updateById(address);
    }

    @Override
    public void deleteAddress(Integer id) {
        super.removeById(id);
    }

    @Override
    public List<Address> getAddressList() {
        return super.list();
    }

       @Override
public Page<Address> getPage(Address address, Page<Address> page) {
    // 构建查询条件
    LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();

    // 添加查询条件
    if (address != null) {
        if (address.getPhone() != null && !address.getPhone().isEmpty()) {
            queryWrapper.eq(Address::getPhone, address.getPhone());
        }
        if (address.getProvince() != null && !address.getProvince().isEmpty()) {
            queryWrapper.eq(Address::getProvince, address.getProvince());
        }
        if (address.getCity() != null && !address.getCity().isEmpty()) {
            queryWrapper.eq(Address::getCity, address.getCity());
        }
    }

    // 执行分页查询
    Page<Address> resultPage = baseMapper.selectPage(page, queryWrapper);

    // 映射user对象
    List<Address> records = resultPage.getRecords();
    for (Address addr : records) {
        if (addr.getUserid() != null) {
            User user = userService.getUserById(addr.getUserid());
            addr.setUser(user);
        }
    }
    resultPage.setRecords(records);

    Long total = this.count(queryWrapper);
    resultPage.setTotal(total);

    return resultPage;
}



    @Override
    public List<Address> getAddressByUserId(Integer userid) {
        return baseMapper.getAddressByUserId(userid);
    }
}
